package 算法.leetcode.stack;

/**
 *
 *  Your MinStack object will be instantiated and called as such:
 *  MinStack obj = new MinStack();
 *  obj.push(x);
 *  obj.pop();
 *  int param_3 = obj.top();
 *  int param_4 = obj.getMin();
 *
 * @author lchenglong
 * @date 2021/1/6
 */
public class MinStack {
    int[] stack;
    int count=0;
    int n;
    Integer min = null;
    /** initialize your data structure here. */
    public MinStack() {
        this.stack = new int[2];
        this.n = stack.length;
        this.count = 0;
    }

    public void push(int x) {
        if (count == n) {
            int[] stack2 = stack;
            stack = new int[2*n];
            for (int i=0;i<count;i++) {
                stack[i]=stack2[i];
            }
            this.n = stack.length;
        }
        stack[count++] = x;
        if (min == null){
            min = x;
        } else {
            min = Math.min(x,min);
        }
    }

    public void pop() {
        if (count == 0) throw new RuntimeException("stack is empty");
        int tmp = stack[count-1];
        --count;
        if (tmp <= min) {
            min = Integer.MAX_VALUE;
            for (int i=0;i<count;i++) {
                min = Math.min(stack[i],min);
            }
        }
    }

    public int top() {
        if (count == 0) throw new RuntimeException("stack is empty");
        int tmp = stack[count-1];
        return tmp;
    }

    public int getMin() {
        return min;
    }

    public static void main(String[] args) {
        // ["MinStack","push","push","push","getMin","pop","top","getMin"]
        //[[],[-2],[0],[-3],[],[],[],[]]
        MinStack stack = new MinStack();
        stack.push(-2);
        stack.push(0);
        stack.push(-3);
        stack.push(7);
        stack.push(4);
        stack.push(11);
        stack.push(6);
        stack.push(4);
        System.out.println(stack.getMin());
        stack.pop();
        System.out.println(stack.top());
        System.out.println(stack.getMin());

    }
}
